﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace jsweb
{
   class HttpProvider
   {
      public delegate void DelHttpContext(HttpListenerContext context);
      public event DelHttpContext IncomingRequest;
      public void InvokeIncomingRequest(HttpListenerContext context)
      {
         DelHttpContext handler = IncomingRequest;
         if (handler != null) handler(context);
      }

      /// <summary>
      /// Listens for incoming web-requests and serves appropriately
      /// </summary>
      /// <param name="url"></param>
      public void Listen(string url)
      {
         var httpListener = new HttpListener();
         httpListener.Prefixes.Add(url);
         httpListener.Start();
         httpListener.BeginGetContext(asyncHttp, httpListener);
      }

      void asyncHttp(IAsyncResult result)
      {
         var listener = result.AsyncState as HttpListener;
         var httpContext = listener.EndGetContext(result);

         // Listen again
         listener.BeginGetContext(asyncHttp, listener);

         // Process request
         InvokeIncomingRequest(httpContext);
      }
   }
}
